package cn.turboinfo.fuyang.api.domain.scheduler.usecase.order

import cn.turboinfo.fuyang.api.domain.common.service.order.ServiceOrderService
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.ServiceOrderPayStatus
import cn.turboinfo.fuyang.api.entity.common.pojo.order.QServiceOrder
import net.sunshow.toolkit.core.qbean.api.request.QPage
import net.sunshow.toolkit.core.qbean.api.request.QRequest
import net.sunshow.toolkit.core.qbean.helper.component.request.QPageRequestHelper
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class SchedulerUnpaidServiceOrderTimeoutUseCase(
    private val serviceOrderService: ServiceOrderService,
) : AbstractUseCase<SchedulerUnpaidServiceOrderTimeoutUseCase.InputData, SchedulerUnpaidServiceOrderTimeoutUseCase.OutputData>() {

    override fun doAction(input: InputData): OutputData {
        val request = QRequest.newInstance()
            .filterEqual(QServiceOrder.payStatus, ServiceOrderPayStatus.UNPAID)
        val requestPage = QPage.newInstance()
            .paging(0, 100)

        val now = LocalDateTime.now()

        QPageRequestHelper.request(request, requestPage, serviceOrderService::findAll)
            .filter {
                // 取已经过了预约时间仍未支付的进行处理
                it.scheduledStartTime.isBefore(now)
            }
            .onEach {
                logger.error { "执行回收未支付订单到超时处理: ${it.id}" }
                serviceOrderService.recycleUnpaidTimeout(it.id)
            }

        return OutputData()
    }

    class InputData : AbstractUseCase.InputData()

    class OutputData : AbstractUseCase.OutputData()

}